import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Input, Select, Table, Tag, Tooltip } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { observer } from 'mobx-react-lite';

import Des from '@/components/des';
import Dict from '@/components/dict';
import Filter from '@/components/filter';
import SearchInput from '@/components/search-input';
import Text from '@/components/text';

import { useStore } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { LevelObj, MethodObj } from '@/enum/log';
import { apiLogPage } from '@/services/base/quanxianmokuaixitongjiekourizhijiekou';
import { formatDate, formatValue } from '@/utils';

import Detail, { DetailRef } from './detail';

/** 该模块增删改查对象 */
export type BizObject = BASE.ApiLog;

const Page: React.FC = () => {
  const store = useStore();
  const permission = usePermission();
  const detail = useRef<DetailRef>(null);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, time, ...formData }) => {
      const [endBeginTime, endEndTime] = ((time as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );

      const res = await apiLogPage({
        ...formData,
        ...id,
        endBeginTime,
        endEndTime,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="id">
          <SearchInput
            style={{
              width: 120 * 3
            }}
            typeList={[
              { value: 'username', children: '用户名' },
              { value: 'fullName', children: '用户姓名' }
            ]}
          />
        </Filter.Item>

        <Filter.Item name="logLevel">
          <Select
            placeholder="日志级别"
            style={{
              width: 120
            }}
            options={Array.from(LevelObj).map(([value, { text }]) => ({ value, label: text }))}
          />
        </Filter.Item>

        <Filter.Item name="clientType">
          <Select
            placeholder="客户端类型"
            style={{
              width: 120
            }}
            options={(store.dict['clientType'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }))}
          />
        </Filter.Item>

        <Filter.Item name="reqApi">
          <Input placeholder="接口地址" />
        </Filter.Item>

        <Filter.Item name="time">
          <DatePicker.RangePicker showTime placeholder={['请求开始时间', '请求结束时间']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '日志级别',
            dataIndex: 'logLevel',
            render: (v) => {
              const obj = LevelObj.get(v);

              if (!obj) {
                return emptyText;
              }

              return <Tag color={obj.color}>{obj.text}</Tag>;
            }
          },
          {
            title: '请求源',
            render: (_, r) => {
              return (
                <Des>
                  <Des.Item label="请求IP" value={formatValue(r.reqIp)} />
                  <Des.Item label="浏览器" value={formatValue(r.browser)} />
                  <Des.Item label="操作系统" value={formatValue(r.systemName)} />
                  <Des.Item label="请求城市" value={formatValue(r.reqCity)} />
                </Des>
              );
            }
          },
          {
            title: '请求接口',
            render: (_, r) => {
              return (
                <Des>
                  <Des.Item
                    label="接口"
                    value={
                      <>
                        <Tag color={MethodObj.get(r.reqType)?.color}>
                          {MethodObj.get(r.reqType)?.text}
                        </Tag>
                        {r.reqApi.length > 30 ? (
                          <Tooltip title={r.reqApi}>
                            <Tag color="blue">{r.reqApi.slice(0, 30)}...</Tag>
                          </Tooltip>
                        ) : (
                          <Tag color="blue">{r.reqApi}</Tag>
                        )}
                      </>
                    }
                  />
                  <Des.Item label="接口描述" value={formatValue(r.logExplain)} />
                  {/* <Des.Item label="请求参数" value={r.reqParam} />
                  <Des.Item label="headers" value={r.reqHeader} /> */}
                </Des>
              );
            }
          },
          {
            title: '请求返回',
            render: (_, r) => {
              const status =
                r.resStatus === 200 ? (
                  <Tag color="green">{r.resStatus}</Tag>
                ) : (
                  <Tag color="red">{r.resStatus}</Tag>
                );

              return (
                <Des>
                  <Des.Item label="状态" value={status} />
                  <Des.Item label="说明" value={r.resMessage} />
                  {/* <Des.Item label="返回数据" value={r.resStr} /> */}
                </Des>
              );
            }
          },
          {
            title: '请求时间',
            render: (_, r) => {
              return (
                <Des>
                  <Des.Item
                    label="开始"
                    value={<Text>{formatDate(r.startTime, 'YYYY-MM-DD HH:mm:ss')}</Text>}
                  />
                  <Des.Item
                    label="结束"
                    value={<Text>{formatDate(r.endTime, 'YYYY-MM-DD HH:mm:ss')}</Text>}
                  />
                  <Des.Item label="距今" value={<Text>{dayjs(r.startTime).fromNow()}</Text>} />
                  <Des.Item
                    label="耗时"
                    value={<Text>{formatValue(((r.costTime || 0) / 1000).toFixed(3))}s</Text>}
                  />
                  <Des.Item
                    label="创建时间"
                    value={<Text>{formatDate(r.createTime, 'YYYY-MM-DD HH:mm:ss')}</Text>}
                  />
                </Des>
              );
            }
          },
          {
            title: '请求用户',
            render: (_, r) => {
              if (String(r.userId) === '0') {
                return formatValue();
              }

              return (
                <Des>
                  <Des.Item label="用户id" value={formatValue(r.userId)} />
                  <Des.Item
                    label="用户类型"
                    value={<Dict dicCode="userType" value={r.userType} />}
                  />
                  <Des.Item label="用户姓名" value={formatValue(r.fullName)} />
                  <Des.Item label="用户名" value={formatValue(r.username)} />
                  <Des.Item
                    label="请求客户端"
                    value={<Dict dicCode="clientType" value={r.clientType} />}
                  />
                </Des>
              );
            }
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        detail.current?.open({
                          rowData: row
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Detail ref={detail} />
    </>
  );
};

export default observer(Page);
